# iris数据集 支持向量机 SVM算法
# 采用  ECOC编码   sklearn.multiclass.OutputCodeClassifier
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn import datasets
import sklearn
import numpy as np
from sklearn.model_selection import train_test_split  # 更新
from sklearn.multiclass import OutputCodeClassifier

np.random.seed(2023)
iris = datasets.load_iris()
x_data = iris.data
y_data = iris.target

# 随机抽取30%的测试集
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.4)

print(x_train.shape,y_train.shape,x_test.shape,y_test.shape)

# 建立SVM
# svm = SVC(C=1.0)  # 默认SVM设置  rbf核函数
# svm = SVC(C=1.0, degree=3, kernel='poly')   # 3次多项式核函数
svm = SVC(C=1.0, kernel='linear')           # 线性核函数
ecoc = OutputCodeClassifier(svm, code_size=3, random_state=2023)
ecoc.fit(x_train, y_train)

# print(svm.support_vectors_)

###################  评估数据集
score=ecoc.score(x_train, y_train)
print(score)
score=ecoc.score(x_test, y_test)              # 检测入册
print(score)

y_pred = ecoc.predict(x_test)
print(y_pred)

from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
print('混淆矩阵：\n', confusion_matrix(y_test, y_pred))
report = classification_report(y_test, y_pred)##
print(report)